/*
 * Copyright 2012 Faculty of Informatics - Masaryk University.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.pa165.creatures.rest.client.services.impl;

import cz.muni.fi.pa165.creatures.dto.WeaponDTO;
import cz.muni.fi.pa165.creatures.dto.mapping.WeaponMapping;
import cz.muni.fi.pa165.creatures.model.Weapon;
import cz.muni.fi.pa165.creatures.rest.client.services.CRUDService;
import cz.muni.fi.pa165.creatures.rest.client.services.utils.CRUDServiceHelper;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

/**
 * This class implements CRUD operations for
 * {@link cz.muni.fi.pa165.creatures.model.Weapon} entity.
 *
 * @author smikloso
 */
public class WeaponCRUDServiceImpl implements CRUDService<WeaponDTO> {

    private static final Logger logger =
            Logger.getLogger(WeaponCRUDServiceImpl.class.getName());

    private static final Class<Weapon> WEAPON_CLASS =
            cz.muni.fi.pa165.creatures.model.Weapon.class;

    private WeaponMapping weaponMapping;

    private JAXBContext context;

    private String uri;

    /**
     * @param uri URI of the resource we contact
     * @throws IllegalArgumentException when {@code uri} is null object.
     */
    public WeaponCRUDServiceImpl(String uri)
            throws IllegalArgumentException, JAXBException {
        if (uri != null) {
            this.uri = uri;
        } else {
            throw new IllegalArgumentException("http uri is null");
        }
        weaponMapping = new WeaponMapping();
        try {
            context = JAXBContext.newInstance(WEAPON_CLASS);
        } catch (JAXBException ex) {
            context = null;
            logger.log(Level.SEVERE,
                    "unable to create JAXBContext instance for Weapon object",
                    ex);
            throw ex;
        }
    }

    @Override
    public void create(WeaponDTO dto) {
        PostMethod postMethod = new PostMethod(uri);
        StringWriter writer = new StringWriter();

        try {
            context.createMarshaller().marshal(
                    weaponMapping.DTOtoEntity(dto), writer);
        } catch (JAXBException ex) {
            logger.log(Level.INFO, "Unable to marshall CreatureDTO {0}", dto);
            return;
        }

        RequestEntity entity = new InputStreamRequestEntity(
                new ByteArrayInputStream(writer.toString().getBytes()));
        postMethod.setRequestEntity(entity);
        CRUDServiceHelper.send(postMethod);
    }

    @Override
    public void getById(Long id) {
        GetMethod getMethod = new GetMethod(uri + "/" + id);
        CRUDServiceHelper.send(getMethod);
    }

    @Override
    public void update(WeaponDTO dto) {
        PutMethod putMethod = new PutMethod(uri);
        StringWriter writer = new StringWriter();

        try {
            context.createMarshaller().marshal(
                    weaponMapping.DTOtoEntity(dto), writer);
        } catch (JAXBException ex) {
            logger.log(Level.INFO, "Unable to marshall WeaponDTO {0}", dto);
            return;
        }

        RequestEntity entity = new InputStreamRequestEntity(
                new ByteArrayInputStream(writer.toString().getBytes()));
        putMethod.setRequestEntity(entity);
        CRUDServiceHelper.send(putMethod);
    }

    @Override
    public void delete(Long id) {
        DeleteMethod deleteMethod = new DeleteMethod(uri + "/" + id);
        CRUDServiceHelper.send(deleteMethod);
    }

    @Override
    public void getAll() {
        GetMethod getMethod = new GetMethod(uri + "/all");
        CRUDServiceHelper.send(getMethod);
    }

    @Override
    public void getCount() {
        GetMethod getMethod = new GetMethod(uri + "/count");
        CRUDServiceHelper.send(getMethod);
    }

}
